##############
# PARAMETERS #
##############

DEBUG_MODE = no

########
# VARS #
########

#{{{#

QMAKE        = qmake
DOXYGEN      = doxygen
VALG         = valgrind
VALG_FLAGS   = --track-origins=yes
VALG_FLAGS_P = --leak-check=full --show-reachable=yes
GDB          = gdb
CD           = cd
ECHO         = echo
RM           = rm -fr
BROWSER      = firefox
PDF_VIEWER   = evince
TXT_VIEWER   = less
COMPRESSER   = tar cvzf

EXEC_D         = Tetris_debug
EXEC_R         = Tetris_release
DOX_CONFIG     = config.dox
DOC_DIR        = documentation
SOURCES        = ./src/
LOG_COMPIL     = compil.log
LOG_VALG       = memory.log

#}}}#

####################
# VARS CALCULATION #
####################

#{{{#

# Compil in mode debug or not ?

	ifeq ($(DEBUG_MODE), yes)
		EXEC = $(EXEC_D)
	else
		EXEC = $(EXEC_R)
	endif

# Is there already documentation ?

	DOC_EXIST    = $(shell if [ -e $(DOC_DIR)/html/index.html -a -e $(DOC_DIR)/latex/Makefile ]; \
	                       then $(ECHO) yes; \
	                       else $(ECHO) no; \
	                       fi)

# What to do before display documentation
	ifeq ($(DOC_EXIST), yes)
		DOC_ON_DISP  =
	else
		DOC_ON_DISP  = doc
	endif

# What to do before display documentation in latex

	DOC_ON_DISP_TEX  = $(shell if [ -e $(DOC_DIR)/latex/refman.pdf ]; \
	                           then $(ECHO) $(ECHO) "Already compiled"; \
	                           else $(ECHO) $(MAKE); \
	                           fi)

#}}}#

################
# MAKE OPTIONS #
################

all: $(EXEC)
	@($(ECHO) "Compilation done")

$(EXEC):
	@($(ECHO) "Compilation log in : $(LOG_COMPIL)")
	@($(ECHO) "Compilation error :")
	@($(ECHO) "---------------------------------")
	@($(CD) $(SOURCES) && $(QMAKE) $(EXEC).pro && $(MAKE) > ../$(LOG_COMPIL)) # display only errors
	@($(ECHO) "---------------------------------")

debug: all
	@($(GDB) ./$(EXEC))

memory_check: all
	@($(VALG) $(VALG_FLAGS) ./$(EXEC))

memory_check_track_leaks:
	@($(ECHO) "$(VALG) log in : $(LOG_VALG)")
	@($(VALG) $(VALG_FLAGS) $(VALG_FLAGS_P) ./$(EXEC) 2> $(LOG_VALG))

doc:
	@($(CD) $(SOURCES) && $(DOXYGEN) ../$(DOX_CONFIG))

doc_display_html: $(DOC_ON_DISP)
	@($(BROWSER) $(DOC_DIR)/html/index.html &)

doc_display_latex: $(DOC_ON_DISP)
	@($(CD) $(DOC_DIR)/latex && $(DOC_ON_DISP_TEX) && $(PDF_VIEWER) refman.pdf &)

doc_archive: doc
	@($(COMPRESSER) $(DOC_DIR).tar.gz $(DOC_DIR))

mrproper: clean doc_clean
	@($(CD) $(SOURCES) && $(QMAKE) $(EXEC).pro && $(MAKE) distclean)
	@($(ECHO) "Project is cleaner as possible !")

doc_clean:
	@($(RM) $(DOC_DIR))
	@($(RM) $(DOC_DIR).tar.gz)
	@($(ECHO) "Documentation deleted !")

clean:
	@($(RM) $(EXEC_R) $(EXEC_D))
	@($(CD) $(SOURCES) && $(QMAKE) $(EXEC).pro && $(MAKE) clean)
	@($(RM) *.log)
	@($(ECHO) "Project is clean !")

